<?php
class child_c2_task_model{




	//视频注入地址
	static $media_url='http://172.31.208.48:9000/vodiis/vodInject!doVideoSliceMethod.action?group=mgtv&desturl=http%3A%2F%2F172.31.208.124%2Fnn_mgtvbk_jsyx%2Fmgtv%2Fjsyx%2Fnotify%2Fnotify_video.php';
	//节目类型更新地址
	static $media_category_update ='http://172.31.208.48:9000/vodiis/vodInject!inject.action?action=doTypeUpdate&CPCode=1004&desturl=';
	//节目类型添加地址
	static $media_category ='http://172.31.208.48:9000/vodiis/vodInject!inject.action?action=doTypeAdd&CPCode=1004&desturl=';
	//节目添加地址
	static $asset_add_url='http://172.31.208.48:9000/vodiis/vodInject!inject.action?action=doProgramAdd&CPCode=1004&desturl=';
	//节目更新地址
	static $asset_update_url='http://172.31.208.48:9000/vodiis/vodInject!inject.action?action=doProgramUpdate&CPCode=1004&desturl=';
	//剧集添加地址
	static $clip_add_url='http://172.31.208.48:9000/vodiis/vodInject!inject.action?action=doEpisodeAdd&CPCode=1004&desturl=http%3A%2F%2F172.31.208.124%2Fnn_mgtvbk_jsyx%2Fmgtv%2Fjsyx%2Fnotify%2Fnotify_video.php';
	//剧集更新地址
	static $clip_update_clip='http://172.31.208.48:9000/vodiis/vodInject!inject.action?action=doEpisodeUpdate&CPCode=1004&desturl=http%3A%2F%2F172.31.208.124%2Fnn_mgtvbk_jsyx%2Fmgtv%2Fjsyx%2Fnotify%2Fnotify_video.php';


	static $CP_CODE = '1004';

 


	/**
	 * 添加内容栏目
	 */
	static public function add_categoy($category_info,$sp_id){
		$action = 'REGIST';
		return self::do_category($category_info,$action,$sp_id,self::$media_category);
	}
	/**
	 * 添加内容栏目
	 */	
	static public function update_category($category_info,$sp_id){
		$action = 'UPDATE';
		return self::do_category($category_info,$action,$sp_id,self::$media_category_update);
	}
	
	/**
	 * 内容栏目
	 * $category_info array(
	 * 'nns_category_id'
	 * 'nns_parent_id'
	 * 'nns_name'
	 * )
	 */
	static public function do_category($category_info,$action,$sp_id,$url){

		$xml = '<?xml version="1.0" encoding="UTF-8"?>';
		$xml .='<TYPE_LIST>';
		//if((int)$category_info['nns_parent_id']>1)
		//{
			$category_info['nns_parent_id'] = 0;
		//}
		$category_info['nns_category_id'] = 'mgtv'.$category_info['nns_category_id'];
		$xml .='<TYPE TYPE_NAME="'.$category_info['nns_name'].'" TYPE_CODE="'.$category_info['nns_category_id'].'" F_TYPE_CODE="'.$category_info['nns_parent_id'].'" CP_CODE="'.self::$CP_CODE.'" />';
		$xml .='</TYPE_LIST>';
		$file_name = 'category_'.$category_info['nns_category_id'].'_'.$action.'.xml';
		$c2_info = array(
			'nns_task_type'=>'Category',
			'nns_task_id'=> isset($category_info['nns_task_id'])?$category_info['nns_task_id']:null,
			'nns_task_name'=> isset($category_info['nns_task_name'])?$category_info['nns_task_name']:null,
			'nns_action'=>	$action,
			'nns_url' => $file_name,
			'nns_content' => $xml,
			'nns_desc' => 'Category,'.$action,
			'push_url' => $url,
		);
		return self::execute_c2_child($c2_info,$sp_id);
	}
	
	



	//如果没有收缩到任务名称

	static public function get_task_name($task_id){
		$db = nn_get_db(NL_DB_READ);
		$sql = "select nns_name from nns_mgtvbk_c2_task where nns_id='$task_id'";
		return nl_db_get_col($sql, $db);
	}




	//修改连续剧
	static public function update_series($vod_info,$sp_id){
		$action = 'UPDATE';
		return self::do_series($vod_info,$action,$sp_id,self::$asset_update_url);
	}
	//添加连续剧
	static public function add_series($vod_info,$sp_id){
		$action = 'REGIST';
		return self::do_series($vod_info,$action,$sp_id,self::$asset_add_url);
	}
	//连续剧
	static public function do_series($vod_info,$action,$sp_id,$url){
		$db = nn_get_db(NL_DB_READ);
		//更新$vod_id
		$vod_id = $vod_info['nns_id'];
		$program_id = $vod_id;
		include dirname(dirname(dirname(__FILE__))).'/'.$sp_id.'/define.php';

		if(empty($vod_info['nns_task_name'])){
			$vod_info['nns_task_name'] = self::get_task_name($vod_info['nns_task_id']);
		}		
		if(empty($vod_info['nns_name'])){
			$vod_info['nns_name'] = $vod_info['nns_task_name'];
		}
		
		
		
		
		
		$xml_str = '<?xml version="1.0" encoding="UTF-8" ?>';
		$xml_str .='<PROFRAM_LIST>';
		
		
		//栏目	
		$category = array();
		if(!empty($vod_info['nns_category_id'])){

			if(is_array($vod_info['nns_category_id'])){
				foreach($vod_info['nns_category_id'] as $nns_category_id){					
					$category[]= 	'mgtv'.$nns_category_id;
				}
			}else if(is_string($vod_info['nns_category_id'])){
				$category[]= 	'mgtv'.$vod_info['nns_category_id'];
			}
		}
		
		//图片
		$pic_url = '';
		if(!empty($vod_info['nns_image2'])){
				$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image2']);
				$file_img = dirname(dirname(dirname(__FILE__))).'/data/downimg/'.$img_save_name;
				if(file_exists($file_img)){
					$pic_url = self::get_image_url($img_save_name,$sp_id);
				}
		}
		
		
		//导演
		$director = array();
		$sql = "select l.* from nns_video_label l ,nns_video_label_bind_1005 b where l.nns_id=b.nns_label_id and b.nns_video_id='".$program_id."' ";
		$dy_result = nl_db_get_all($sql,$db);
		if(is_array($dy_result)){
			foreach($dy_result as $label){
				$director[] = $label['nns_name'];
			}
		}
		
		//演员
		$actor = array();
		$sql = "select l.* from nns_video_label l ,nns_video_label_bind_1006 b where l.nns_id=b.nns_label_id and b.nns_video_id='".$program_id."' ";
		$yy_result = nl_db_get_all($sql,$db);
		if(is_array($yy_result)){
			foreach($yy_result as $label){
				$actor[] = $label['nns_name'];
			}
		}
		
		$xml_str .='<PROGRAM NAME="'.htmlspecialchars($vod_info['nns_name'], ENT_QUOTES).'"  CM_CP_PROGRAM_CODE="'.$vod_id.'" CP_CODE="'.self::$CP_CODE.'" TYPE_CODE="'.implode(",", $category).'" F_TYPE_CODE="" COVER="'.$pic_url.'" DIRECTOR="'.implode(",", $director).'" ACTOR ="'.implode(",", $actor).'" DESC="'.htmlspecialchars($vod_info['nns_summary'], ENT_QUOTES).'"  PLAYTYPE="1"  SHOWTIME="' . date('Ymd',strtotime($vod_info['nns_show_time'])).'" ALIAS="'.htmlspecialchars($vod_info['nns_alias_name'], ENT_QUOTES).'" SORCE="'.$vod_info['nns_point'].'"  TNUM="'.$vod_info['nns_all_index'].'" />';
		$xml_str .='</PROFRAM_LIST>';
		$guid = np_guid_rand();
		$file_name = 'series_'.$vod_id.'_'.$action.'_'.$guid.'.xml';

		
		$c2_info = array(
			'nns_task_type'=>'Series',
			'nns_task_id'=> isset($vod_info['nns_task_id'])?$vod_info['nns_task_id']:null,	
			'nns_task_name'=> isset($vod_info['nns_task_name'])?$vod_info['nns_task_name']:null,	
			'nns_action'=>	$action,		
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Series,'.$action,
			'push_url' => $url,
		);		
		return self::execute_c2_child($c2_info,$sp_id);

	}
	/**
	 * 点播内容/点播分集
	 * $vod_info array(
	 * 'nns_id'   影片id/分集id
	 * 'nns_vod_id' 分集属于影片id
	 * 'nns_category_id'  影片的栏目id
	 * 'nns_series_flag' 连续剧分集标识
	 * )
	 * 目前实现上，给对方的影片id都是我方的分集id，因为片源是和分集关联的；
	 * 所以在删除影片时，也是用分集id删除
	 */
	static public function do_vod($vod_info,$action,$sp_id,$url){
		//$action = 'REGIST';
		include dirname(dirname(dirname(__FILE__))).'/'.$sp_id.'/define.php';	
		$program_id = $vod_info['nns_id'];//vod nns_vod_id index nns_vod_index_id
		$db = nn_get_db(NL_DB_READ);	
		$sql = "select * from nns_vod_media where nns_vod_id='{$vod_info['nns_vod_id']}'  and nns_vod_index_id='{$program_id}' and nns_vod_index='{$vod_info['nns_index']}' and nns_deleted!=1 order by nns_kbps desc limit 1";		
		$media_mode_filter = get_config_v2('g_cp_media_filter');
		$mode_filter = '';
		if(!empty($media_mode_filter['media_mode']) && is_array($media_mode_filter['media_mode']))
		{
			$mode_filter = implode("','", $media_mode_filter['media_mode']);
			$mode_filter = "'{$mode_filter}'";
		}
		if(!empty($mode_filter))
		{
			$sql = "select * from nns_vod_media where nns_vod_id='{$vod_info['nns_vod_id']}'  and nns_vod_index_id='{$program_id}' and nns_vod_index='{$vod_info['nns_index']}' and nns_deleted!=1 and nns_mode not in ({$mode_filter}) order by nns_kbps desc limit 1";
		}
		$result = nl_db_get_one($sql,$db);
		$media_id = null;
		if(is_array($result)){
			$media_id = $result['nns_id'];
		}
		
		if(empty($media_id))
		{
			return false;
		}

		if(empty($vod_info['nns_task_name'])){
			$vod_info['nns_task_name'] = self::get_task_name($vod_info['nns_task_id']);
		}		
		if(empty($vod_info['nns_name'])){
			$vod_info['nns_name'] = $vod_info['nns_task_name'];
		}
		
		
		$xml_str ='<?xml version="1.0" encoding="UTF-8" ?>';
		$xml_str .= '<EPISODE_LIST>';
		$sequence = $vod_info['nns_index']+1;
		if(empty($vod_info['nns_time_len']))
		{
			$vod_info['nns_time_len'] = 0;
		}
		$summary = htmlspecialchars($vod_info['nns_summary'], ENT_QUOTES);
		$xml_str .= '<EPISODE NAME="'.htmlspecialchars($vod_info['nns_name'], ENT_QUOTES).'"  CM_CP_PROGRAM_CODE="'.$vod_info['nns_vod_id'].'" CP_CODE="'.self::$CP_CODE.'" CM_CP_EPISODE_CODE="'.$program_id.'" NUM="'.$sequence.'" NOTE="'.mb_strcut($summary, 0,500,'utf-8').'" LENGTH="'.$vod_info['nns_time_len'].'" VIDEO_CODE="'.$media_id.'" VIDEO_NAME="'.htmlspecialchars($vod_info['nns_name'], ENT_QUOTES).'" />';
		$xml_str .= '</EPISODE_LIST>';



		
		$guid = np_guid_rand();		
		$file_name = 'program_'.$vod_info['nns_series_flag'].'_'.$program_id.'_'.$action.'_'.$guid.'.xml';

		$c2_info = array(
			//'nns_id' => $c2_info['c2_id'],
			'nns_task_type'=>'Program',
			'nns_task_id'=> isset($vod_info['nns_task_id'])?$vod_info['nns_task_id']:null,	
			'nns_task_name'=> isset($vod_info['nns_task_name'])?$vod_info['nns_task_name']:null,
			'nns_action'=>	$action,			
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Program,'.$action,
			'push_url' => $url,
		);		
		return self::execute_c2_child($c2_info,$sp_id);
	}

	static public function get_image_url($img_path,$sp_id){
		include dirname(dirname(__FILE__)).'/'.$sp_id.'/define.php';
		if(defined('HW_DOANLOAD_IMG_METHOD') && HW_DOANLOAD_IMG_METHOD=='ftp'){
			$img_url = HW_DOANLOAD_IMG_FTP.$img_path;
		}else{
			$img_url = nl_image::epg_video_image_url($img_path);
		}
		return $img_url;
	}

	//修改点播
	static public function update_vod($vod_info,$sp_id){
		// 		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
		// 			if(method_exists('child_c2_task_model','update_vod')){
		// 				$re = child_c2_task_model::update_vod($vod_info,$sp_id);
		// 				return $re;
		// 			}
		// 		}

		$action = 'UPDATE';
		return self::do_vod($vod_info,$action,$sp_id,self::$clip_update_clip);
	}

	//添加点播
	static public function add_vod($vod_info,$sp_id){

		//print_r($vod_info);

		//echo $sp_id;
		//echo dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
		// 		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
		// 			if(method_exists('child_c2_task_model','add_vod')){
		// 				$re = child_c2_task_model::add_vod($vod_info,$sp_id);
		// 				return $re;
		// 			}
		// 		}

		//die;

		$action = 'REGIST';
		return self::do_vod($vod_info,$action,$sp_id,self::$clip_add_url);
	}

	/**
	 * params
	 */
	static public function delete_vod($params,$sp_id){

		// 		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
		// 			if(method_exists('child_c2_task_model','delete_vod')){
		// 				$re = child_c2_task_model::delete_vod($params,$sp_id);
		// 				return $re;
		// 			}
		// 		}

		$action = 'DELETE';
		$program_id = $params['nns_id'];
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Program" ID="' .$program_id. '" Action="' . $action . '" Code="' .$program_id. '">';	
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';		//	
		$file_name = 'program_'.$program_id.'_'.$action.'.xml';
		$c2_info = array(
			'nns_task_type'=>'Program',
			'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,	
			'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:null,
			'nns_action'=>	$action,			
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Program,'.$action,
		);
		return self::execute_c2_child($c2_info,$sp_id);

	}
	/**
	 * 此方法不建议使用
	 * $params array('nns_ids')
	 */
	static public function delete_vods($params){
		$action = 'DELETE';

		//$program_id = $params['nns_id'];
		//self::do_vod($vod_info,$action);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';	
		foreach($params['nns_ids'] as $id){
			$xml_str .= '<Object ElementType="Program" ID="' .$id. '" Action="' . $action . '" Code="' .$id. '">';	
			$xml_str .= '</Object>';			
		}

		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';
		//	
		$guid = np_guid_rand();
		$file_name = 'program_'.$guid.'_'.$action.'.xml';
		//

		$c2_info = array(
			'nns_id' => $c2_info['c2_id'],
			'nns_task_type'=>'Program',
			'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,
			'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:null,	
			'nns_action'=>	$action,			
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			//'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
			'nns_desc' => 'Program,'.$action,
		);		
		return self::execute_c2_child($c2_info);

	}	
	/**
	 * 注入片源（以分集为单位,切片完成后调用）
	 * $index_media array(
	 * 'nns_video_id'
	 * 'nns_video_index_id'
	 * 'nns_task_id'
	 * 'nns_new_dir'
	 * 'nns_media_ids'
	 * )
	 */
	static public function add_movies_by_vod_index($index_media,$sp_id){
		include_once dirname(dirname(dirname(__FILE__))).'/'.$sp_id.'/define.php';
		//include_once dirname(dirname(dirname(__FILE__))).'/models/content_task_model.php';
		include_once dirname(dirname(dirname(__FILE__))).'/models/clip_task_model.php';	
		DEBUG && i_write_log_core('--注入片源--');
		$db = nn_get_db(NL_DB_WRITE);
		$sql = "select nns_pinyin from nns_vod where nns_id='".$index_media['nns_video_id']."'";
		$pinyin = nl_db_get_col($sql,$db);
		$action = 'REGIST';


		$sql = "select * from nns_vod_media where nns_deleted != 1 and nns_vod_id='{$index_media['nns_video_id']}' and nns_vod_index_id='{$index_media['nns_video_index_id']}' and nns_id='{$index_media['nns_media_id']}' order by nns_kbps desc limit 1";

		$medias = nl_db_get_all($sql,$db);
		
		
		$sql_c2_index = "select nns_id from nns_mgtvbk_c2_task where nns_org_id='".$sp_id."' and nns_type='index' and nns_ref_id='".$index_media['nns_video_index_id']."' and nns_src_id='".$index_media['nns_video_id']."'";
		$c2_index_task_id = nl_db_get_col($sql_c2_index,$db);
		if($c2_index_task_id)
		{
			//content_task_model::vod($c2_index_task_id,null,$sp_id);
		}

		//更新$index_media_id
		$index_media_detail = video_model::get_vod_media_info($index_media['nns_media_id']);
		//$index_media_id = '000000'.$index_media_detail['nns_integer_id'];
		$index_media_id = $index_media['nns_media_id'];

		//更新$index_media_index_id
		$index_media_index_detail = video_model::get_vod_medias_by_index($index_media['nns_video_index_id']);
		//$index_media_index_id = '000000'.$index_media_index_detail['nns_integer_id'];
		$index_media_index_id = $index_media['nns_video_index_id'];

		if(is_array($medias) && count($medias)>0){
			                
			//判断片源的URL	
			if(empty($index_media['nns_date'])){
				$index_media['nns_date'] = nl_db_get_col("select nns_date from nns_mgtvbk_clip_task where nns_id='{$index_media['nns_clip_task_id']}'", $db);
			}		
			$url = MOVIE_FTP.$index_media['nns_date'].'/'.$index_media['nns_clip_task_id'].'/'.$pinyin.'-'.$media['nns_vod_index'].'.m3u8';
			if(!empty($index_media['nns_file_path'])){
				$url = MOVIE_FTP.$index_media['nns_file_path'];
			}


			$xml_str ='<?xml version="1.0" encoding="utf-8"?>';
			$xml_str .='<STREAM action="add">';
			$xml_str .='<URL videoID="'.$index_media['nns_media_id'].'" Type="TS">'.$url.'</URL>';
			$xml_str .='</STREAM>';
			
			


			//die($xml_str);
			$guid = np_guid_rand();
			$file_name = 'vod_media_'.$index_media_id.'_'.$action.'_'.$guid.'.xml';


			$c2_info = array(
				//'nns_id' => $c2_info['c2_id'],
				'nns_task_type'=>'Movie',
				'nns_task_id'=> isset($index_media['nns_task_id'])?$index_media['nns_task_id']:null,
				'nns_task_name'=> isset($index_media['nns_task_name'])?$index_media['nns_task_name']:null,	
				'nns_action'=>	$action,				
				'nns_url' => $file_name,
				'nns_content' => $xml_str,
				//'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
				'nns_desc' => 'Movie,'.$action,
				'push_url' => self::$media_url,
			);



			//修改切片的状态

			$clip_task_id = $index_media['nns_clip_task_id'];



			//更改状态
			$dt = date('Y-m-d H:i:s');
			$set_state = array(
				'nns_state' => clip_task_model::TASK_C_STATE_C2_HANDLE,
				'nns_desc' => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_HANDLE],
				'nns_modify_time'=>$dt,
			);
			clip_task_model::update_task($clip_task_id, $set_state);


			//任务日志	
			$task_log = array(
				'nns_task_id' => $clip_task_id,
				'nns_state'   => clip_task_model::TASK_C_STATE_C2_HANDLE,
				'nns_desc'    => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_HANDLE],
			);	
			clip_task_model::add_task_log($task_log);



			return self::execute_c2_child($c2_info,$sp_id);

		}else{
			DEBUG && i_write_log_core('--没有片源--');
			nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=1,nns_action='destroy',nns_epg_status=97 where nns_id='{$index_media['nns_task_id']}'", $db);
		}

	}
	
	
	
	/**
	 * 使用本方法时，请以分集为单位
	 * $params array(
	 * nns_ids
	 * )
	 */
	//static public function delete_movies($params,$sp_id){
		/*$action = 'DELETE';
		$xml_str = '<?xml version="1.0" encoding="utf-8"?>';
		$xml_str .= '<STREAM action="del">';
　　　		$xml_str .= '<videoID>'.$params['nns_id'].'</videoID>';
		$xml_str .= '</STREAM>';
		$guid =  np_guid_rand();
		$file_name = 'movies_'.$guid.'_'.$action.'.xml';
		$c2_info = array(
			'nns_task_type'=>'Movie',
			'nns_task_id'=>  isset($params['nns_task_id'])?$params['nns_task_id']:null,
			'nns_task_name'=>  isset($params['nns_task_name'])?$params['nns_task_name']:null,		
			'nns_action'=>	$action,		
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Movie,'.$action,
			'push_url' => self::$media_url,
		);		
		return self::execute_c2_child($c2_info,$sp_id);
		*/
	//}
	



	static public function delete_movies($params,$sp_id){
		$action = 'DELETE';
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?>';
		$xml_str .= '<STREAM action="del">';
		$xml_str .= '<videoID>'.$params['nns_id'].'</videoID>';
		$xml_str .= '</STREAM>';
		$guid =  np_guid_rand();
		$file_name = 'movies_'.$guid.'_'.$action.'.xml';
		$c2_info = array(
			'nns_task_type'=>'Movie',
			'nns_task_id'=>  isset($params['nns_task_id'])?$params['nns_task_id']:null,
			'nns_task_name'=>  isset($params['nns_task_name'])?$params['nns_task_name']:null,		
			'nns_action'=>	$action,		
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Movie,'.$action,
			'push_url' => self::$media_url,
		);
		return self::execute_c2_child($c2_info,$sp_id);
	}



	/**
	 * 华为没有处理的指令，再次重发
	 */
	static public function resend_c2_again($sp_id){
		$db = nn_get_db(NL_DB_READ);
		/************超时没返回重发************/
		$time_out = 3600;
		$sql = "select * from nns_mgtvbk_c2_log where nns_org_id='$sp_id' and nns_again=0 and nns_create_time < NOW() - INTERVAL ".$time_out." SECOND  and nns_notify_result is null  order by nns_create_time asc  limit 90";
		$all = nl_db_get_all($sql,$db);	
		if(is_array($all)) {
			foreach($all as $item0){
				self::execute_c2_again($item0['nns_id'],$sp_id);
			}			
		}

		/************以下为失败重发************/
		//连续剧
		$sql = "select * from nns_mgtvbk_c2_log where nns_org_id='$sp_id' and    (nns_notify_result='-1' and (nns_notify_result_url=''  or nns_notify_content like '%Entity queue is full%') or nns_result like '%[-1]soap info is full%') and nns_again=0 order by nns_again asc,nns_create_time asc  limit 90";
		$all = nl_db_get_all($sql,$db);
		if(is_array($all)) {
			foreach($all as $item0){
				self::execute_c2_again($item0['nns_id'],$sp_id);
			}			
		}
	}
	static public function execute_c2_again($nns_id,$sp_id){
		$db = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		$sql = "select * from nns_mgtvbk_c2_log where nns_id='$nns_id'";
		$c2_info = nl_db_get_one($sql,$db);

		/*$count = "select count(1) as num from nns_mgtvbk_c2_log where nns_org_id='{$sp_id}' and nns_task_id='{$c2_info['nns_task_id']}' and nns_task_type='{$c2_info['nns_task_type']}'";
		$c = nl_db_get_col($count, $db);
		if($c>=2){
			return false;
		}*/
		// include_once dirname(dirname(dirname(__FILE__))).'/mgtv/'.$sp_id.'/'.$sp_id.'_client.php';
		// $CmdFileURL = C2_FTP.$c2_info['nns_url'];
		// $c2_info['nns_id'] = np_guid_rand();
		// $c2_info['nns_again'] = 0;
		// unset($c2_info['nns_result'],$c2_info['nns_notify_result_url'],$c2_info['nns_notify_result'],$c2_info['nns_notify_time'],$c2_info['nns_modify_time'],$c2_info['nns_notify_content']);
		// $dt = date('Y-m-d H:i:s');
		// $c2_info['nns_create_time'] = $dt;
		// $c2_info['nns_send_time'] = $dt;
		// $result = call_user_func_array(array($sp_id.'_client', 'ExecCmd'), array($c2_info['nns_id'], $CmdFileURL));
		// $c2_info['nns_result'] = '['.$result->Result.']'.$result->ErrorDescription;
		//$result = jllt_client::ExecCmd($nns_id,$CmdFileURL);
		$sql = "update nns_mgtvbk_c2_log set nns_again=1 ,nns_notify_result='-1',nns_modify_time=now() where nns_id='".$nns_id."'";
		nl_execute_by_db($sql,$db_w);

		if($c2_info['nns_task_id']){
			content_task_model::vod($c2_info['nns_task_id'],null,$sp_id);
		}


		return true;
	}
	/**
	 * 执行C2注入命令
	 * @param $c2_info array(
	 * 'c2_id'
	 * 'file_name'
	 * 'xml_content'
	 * )
	 */
	static public function execute_c2_child($c2_info,$sp_id){
		global $g_webdir;
		$xml_str = $c2_info['nns_content'];

		$c2_id = np_guid_rand();

		//var_dump($c2_info);die;
		if(!self::exists_c2_commond_child($c2_info,$sp_id)){
			$sub_path = date('Y-m-d');
			$file = $c2_info['nns_url'];
			$c2_info['nns_url'] = $sub_path.'/'.$file;
			$xml_str = $c2_info['nns_content'];
			$file_path = dirname(dirname(dirname(dirname(__FILE__)))).'/data/mgtv/'.$sp_id.'/inject_xml/'.$sub_path.'/';
			if(!is_dir($file_path)) mkdir($file_path,0777,true);
			$file_path .= $file;
			file_put_contents($file_path,$xml_str);
			
			$push_url = $c2_info['push_url'];
			unset($c2_info['push_url']);

			$c2_info['nns_id'] = $c2_id;
			$c2_info['nns_result'] = '[0]';
			$bool = false;
			try {
				
				$result= self::__gateway_run($push_url,null,'post',$xml_str,array('content-type: text/xml'));
				DEBUG && i_write_log_core('---------execute  url----------'.var_export($push_url,true),'push');
				DEBUG && i_write_log_core('---------execute  data----------'.var_export($xml_str,true),'push');
				DEBUG && i_write_log_core('---------execute  result----------'.var_export($result,true),'push');
				$bool = false;
				if($result['code'] == '200' ){
					if(strpos($result['data'],'xml'))
					{
						include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/np/np_xml_to_array.class.php';
						$re = np_xml_to_array::parse2($result['data']);
						if(empty($re))
						{
							$c2_info['nns_result'] = '[-1]';
							$bool = false;
						}elseif($re['TYPE']['@attributes']['STATUS']=='0'||$re['PROGRAM']['@attributes']['STATUS']=='0'||$re['EPISODE']['@attributes']['STATUS']=='0'){
							$c2_info['nns_result'] = '[0]';
							$bool = true;
						}
						
						
						if(strpos($result['data'],'已存在')){
							$c2_info['nns_result'] = '[0]';
							$bool = true;
						}
						
						
					}else{
						$c2_info['nns_result'] = '[-1]';
						$bool = false;
					}
					
				}elseif($result['data']=='OK'){
					//$c2_info['nns_result'] = '[-1]';
					$c2_info['nns_result'] = '[0]';
					$bool = true;
				}else{
					$c2_info['nns_result'] = '[-1]';
					$bool = false;
				}
				$result['data'] = trim($result['data']);
				if(strtolower($result['data'])==strtolower('OK')){
					$c2_info['nns_result'] = '[0]';
					$bool = true;
				}
			} catch (Exception $e) {
				$c2_info['nns_result'] = '[-1]';
				$bool = false;
			}
			//$c2_info['nns_result'] = '[0]';
			self::save_c2_log($c2_info,$sp_id);
			//$bool = true;
			if($bool)
			{
				$array = array('nns_id'=>$c2_id,'nns_notify_result'=>0,'nns_notify_result_url'=>false);
				//self::save_c2_notify_child($array);
			}else{
				$array = array('nns_id'=>$c2_id,'nns_notify_result'=>-1,'nns_notify_result_url'=>false);
				
			}
			if($c2_info['nns_task_type']!='Movie'){
				self::save_c2_notify_child($array);
			}
			
			return $bool;
		}
		return false;

	}

	static public function exists_c2_commond_child($c2_info,$sp_id){
		//eturn true;
		set_time_limit(0);
		$db_r = nn_get_db(NL_DB_READ);
		$nns_org_id = $sp_id;
		$nns_task_type = $c2_info['nns_task_type'];
		$nns_task_id = $c2_info['nns_task_id'];
		$nns_action = $c2_info['nns_action'];


		if(empty($nns_task_id)) return false;
		/*$count = "select count(1) as num from nns_mgtvbk_c2_log where nns_org_id='{$sp_id}' and nns_task_id='{$nns_task_id}' and nns_task_type='{$nns_task_type}'";
		$c = nl_db_get_col($count, $db);
		if($c>=2){
			return true;
		}*/

		usleep(5000);
		//if(empty($nns_task_id)) return false;
		$nowtime=date("Y-m-d H:i:s");
		$now_data = date('Y-m-d H:i:s',strtotime("$nowtime-1 hour"));
		$sql = "select 1 from nns_mgtvbk_c2_log where nns_org_id='$nns_org_id' and nns_task_type='$nns_task_type' and nns_task_id='$nns_task_id' and nns_action='$nns_action' and nns_notify_result is null and nns_create_time > NOW() - INTERVAL 3600 SECOND";

		//$sql = "select nns_task_id,count(1) as num from nns_mgtvbk_c2_log where nns_create_time > '".$now_data."' and nns_task_type='Movie' group by nns_task_id,nns_action having count(1)> 2;";
		$data = nl_db_get_all($sql,$db_r);

		if(is_array($data) && count($data)>0){
			return true;
		}
		return false;

		/*
		switch ($nns_task_type) {
			case 'Series':
				$sql = "select * from nns_mgtvbk_c2_task where nns_id='{$nns_task_id}' and nns_org_id='{$nns_org_id}'";
				break;
			case 'Program':
				$sql = "select * from nns_mgtvbk_c2_task where nns_id='{$nns_task_id}' and nns_org_id='{$nns_org_id}'";
				break;
			case 'Movie':
				$sql = "select * from nns_mgtvbk_c2_task where nns_id='{$nns_task_id}' and nns_org_id='{$nns_org_id}'";
				break;
			default:
				return false;
			break;
		}		
		$data = nl_db_get_one($sql,$db_r);
		if(is_array($data)&&$data['nns_status']==5){
			return true;
		}
		return false;*/
	}


	/**
	 * 保存C2命令日志
	 * $c2_log array(
	 * 'nns_id',
	 * 'nns_type',
	 * 'nns_org_id',
	 * 'nns_video_id',
	 * 'nns_video_type',
	 * 'nns_video_index_id',
	 * 'nns_media_id',
	 * 'nns_url',
	 * 'nns_content',
	 * 'nns_result',
	 * 'nns_desc',
	 * 'nns_create_time'
	 * )
	 */
	static public function save_c2_log($c2_log,$sp_id){
		$db = nn_get_db(NL_DB_WRITE);
		//$db->open();
		$c2_log['nns_type'] = 'std';
		$c2_log['nns_org_id'] = $sp_id;
		$dt = date('Y-m-d H:i:s');
		$c2_log['nns_create_time'] = $dt;
		$c2_log['nns_send_time'] = $dt;
		$bool = nl_db_insert($db,'nns_mgtvbk_c2_log',$c2_log);
		DEBUG && i_write_log_core('---------execute  sql----------'.var_export($bool,true),'push');
		return $bool;
	}
	/**
	 * C2通知命令日志
	 * $c2_notify array(
	 * 'nns_id',
	 * 'nns_notify_result_url',
	 * 'nns_notify_result',
	 * 
	 * )
	 */
	static public function save_c2_notify_child($c2_notify){
		
		//die('sdfsdf');
        DEBUG && i_write_log_core('---------save_c2_notify----------');
		$db = nn_get_db(NL_DB_WRITE);
		$dt = date('Y-m-d H:i:s');
		$wh_content ="";
		if($c2_notify['nns_notify_result']!='-1'){
			$wh_content = "nns_content='',";
		}
		$sql = "update nns_mgtvbk_c2_log set " .
				"nns_notify_result_url='".$c2_notify['nns_notify_result_url']."' ," .$wh_content.
				"nns_notify_result='".$c2_notify['nns_notify_result']."', nns_notify_time='".$dt."'," .
				"nns_modify_time='".$dt."' " .
				"where nns_id='".$c2_notify['nns_id']."'";
		nl_execute_by_db($sql,$db);
		
		$db_r = nn_get_db(NL_DB_READ);
		$sql = "select * from nns_mgtvbk_c2_log where nns_id='".$c2_notify['nns_id']."'";
		$c2_info = nl_db_get_one($sql,$db_r);
		if($c2_info==false) return false;
		//如果回馈的消息是重发的消息
		if($c2_info['nns_again']>=1){
			return false;
		}
		if($c2_info['nns_task_type']=='Series' || $c2_info['nns_task_type']=='Program'||$c2_info['nns_task_type']=='Movie'){
			if($c2_notify['nns_notify_result']=='-1'){
				$sql_update = "update nns_mgtvbk_c2_task set nns_status=-1,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";//注入媒体时，再次发送；否则媒体注入没有绑定节目			
				/*if($c2_info['nns_action']=='REGIST'){
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=1,nns_action='modify',nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";//注入媒体时，再次发送；否则媒体注入没有绑定节目			
				}elseif($c2_info['nns_action']=='UPDATE'){
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=1,nns_action='add',nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";//注入媒体时，再次发送；否则媒体注入没有绑定节目
				}*/			
			}else{				
				$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
				
				//是否需要异步获取播放穿
				
				$sp_config = sp_model::get_sp_config($c2_info['nns_org_id']);
				$cdn_query_mediaurl_bool = false;
				if(isset($sp_config['cdn_query_mediaurl'])&&(int)$sp_config['cdn_query_mediaurl']===1){
					$cdn_query_mediaurl_bool = true;
				}				
				if($cdn_query_mediaurl_bool&&$c2_info['nns_task_type']=='Movie'){
					
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=6,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
					$sql_info = "select * from nns_mgtvbk_c2_task where nns_id='{$c2_info['nns_task_id']}'";
					$c2__taskinfo = nl_db_get_one($sql_info,$db_r);
					
					if(is_array($c2__taskinfo)){
						if($c2__taskinfo['nns_status']=='0'){
							$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
						}
					}
					
					if($c2_info['nns_action']=='DELETE'){
						$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
					}
				}
			}
			nl_execute_by_db($sql_update,$db);	
		}

		
		if($c2_info['nns_task_type']=='Movie'){
			include_once dirname(dirname(dirname(__FILE__))).'/models/clip_task_model.php';			
			$sql_c2_task = nl_db_get_one("select * from  nns_mgtvbk_c2_task  where nns_id='".$c2_info['nns_task_id']."'", $db);
			if($c2_info['nns_action']=='DELETE'){
				if($c2_notify['nns_notify_result']=='-1'){
					$nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_FAIL;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_FAIL];
					//$sql = "update nns_mgtvbk_c2_task set nns_status=-1 where nns_id='".$c2_info['nns_task_id']."'";
					//nl_execute_by_db($sql,$db);		
				}else{
					$nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_SUCC;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_SUCC];
					//$sql = "update nns_mgtvbk_c2_task set nns_status=0 where nns_id='".$c2_info['nns_task_id']."'";
					//nl_execute_by_db($sql,$db);		
					
				}
			}else{
				if($c2_notify['nns_notify_result']=='-1'){
					$nns_state = clip_task_model::TASK_C_STATE_C2_FAIL;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_FAIL];
					//$sql = "update nns_mgtvbk_c2_task set nns_status=-1 where nns_id='".$c2_info['nns_task_id']."'";
					//nl_execute_by_db($sql,$db);		
				}else{
					$nns_state = clip_task_model::TASK_C_STATE_C2_SUCC;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_SUCC];
					//$sql = "update nns_mgtvbk_c2_task set nns_status=0 where nns_id='".$c2_info['nns_task_id']."'";
					//if($c2_info['nns_org_id']=='sihua'){
					//	$sql = "update nns_mgtvbk_c2_task set nns_status=6 where nns_id='".$c2_info['nns_task_id']."'";
					//}
					//nl_execute_by_db($sql,$db);		
					
				}
			}
				
			//更改切片状态
			$dt = date('Y-m-d H:i:s');
			$set_state = array(
			'nns_state' => $nns_state,
			'nns_desc' => $nns_desc,
			'nns_modify_time'=>$dt,
			);
			clip_task_model::update_task($sql_c2_task['nns_clip_task_id'], $set_state);
			//任务日志	
			$task_log = array(
			'nns_task_id' => $sql_c2_task['nns_clip_task_id'],
			'nns_state' => $nns_state,
			'nns_desc' => $nns_desc,
			);	
			clip_task_model::add_task_log($task_log);
		}



		// if($c2_info['nns_task_type']=='QueryPlay'){
			// if($c2_notify['nns_notify_result']=='-1'){
				// $sql_update = "update nns_mgtvbk_c2_task set nns_status=9,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
			// }else{
				// $sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97,nns_ex_url='".time()."' where nns_id='".$c2_info['nns_task_id']."'";
			// }
			// nl_execute_by_db($sql_update,$db);
		// }

		//通知列队
		
		if($c2_notify['nns_notify_result']!='-1'){
			//$c2_info['nns_task_id']
			include_once dirname(dirname(dirname(__FILE__))).'/models/queue_task_model.php';
			$queue_task_model = new queue_task_model();
			//print_r($c2_info);
			$queue_task_model->q_report_task($c2_info['nns_task_id']);
			$q_model=null;
		}
		
		//下载结果
		if(!empty($c2_notify['nns_notify_result_url'])){
			$url_arr = parse_url($c2_notify['nns_notify_result_url']);
			$port = isset($url_arr["port"])?$url_arr["port"]:21;
			include_once NPDIR . '/np_ftp.php';
			$ftp1=new nns_ftp($url_arr['host'],$url_arr["user"],$url_arr["pass"],$port);
			$ftpcon1=$ftp1->connect();
            if (empty($ftpcon1)) {          	
                return FALSE;
            }
            $notify_save_path = dirname(dirname(dirname(dirname(__FILE__)))).'/data/mgtv/'.$c2_info['nns_org_id'].'/notify'.$url_arr["path"];
            $path_parts = pathinfo($notify_save_path);
             if (!is_dir($path_parts['dirname'])){
                 mkdir($path_parts['dirname'], 0777, true);
             }            
            $rs = $ftp1->get(ltrim($url_arr["path"],'/'),$notify_save_path);
            if($rs==false){
            	DEBUG && i_write_log_core('---------下载 notify 失败----------');
            	return FALSE;
            }
		}
		
		
		
		
		return true;
	}


	static public function _save_img_from_url($img_file,$img_url){
		$ret_data = array();
		$json_data = null;
		$http_code = null;
		for ($i = 0; $i < 3; $i++) {
			$http_client = new np_http_curl_class();
			$json_data = $http_client->get($img_url);
			$http_code = $http_client->curl_getinfo['http_code'];
			if ($http_code != 200) {
				//i_echo('-----下载失败:'.$img_url);
				continue;
			} else {
				break;
			}
		}
		if ($json_data && $http_code && $http_code == 200) {
			return  file_put_contents($img_file,$json_data);
		}
		return false;
	}

	static public function update_notify_content($nns_id,$nns_notify_content){
		$db = nn_get_db(NL_DB_WRITE);
		$sql = "update nns_mgtvbk_c2_log set nns_notify_content='".$nns_notify_content."' where nns_id='".$nns_id."'";
		return nl_execute_by_db($sql,$db);			
	}
	static public function get_c2_log_list($sp_id,$filter=null,$start=0,$size=100){
		$db = nn_get_db(NL_DB_READ);
		//$db->open();
		$sql = "select  * from nns_mgtvbk_c2_log where nns_org_id='".$sp_id."' ";
		$sql_count = "select  count(*) from nns_mgtvbk_c2_log where nns_org_id='".$sp_id."' ";
		if($filter != null){
			$wh_arr = array();
			if(!empty($filter['nns_task_name'])){
				$wh_arr[] = " nns_task_name like '%".$filter['nns_task_name']."%'";
			}
			if(!empty($filter['nns_id'])){
				$wh_arr[] = " nns_id='".$filter['nns_id']."'";
			}			
			if(!empty($filter['nns_task_type'])){
				$wh_arr[] = " nns_task_type='".$filter['nns_task_type']."'";
			}
			if(!empty($filter['nns_action'])){
				$wh_arr[] = " nns_action='".$filter['nns_action']."'";
			}

			if(!empty($filter['day_picker_start'])){
				$wh_arr[] = " nns_create_time >='".$filter['day_picker_start']."' ";
			}
			if(!empty($filter['day_picker_end'])){
				$wh_arr[] = " nns_create_time <='".$filter['day_picker_end']."' ";
			}
			if(!empty($filter['notify_time_start'])){
				$wh_arr[] = "  nns_notify_time >='".$filter['notify_time_start']."'";
			}
			if(!empty($filter['notify_time_end'])){
				$wh_arr[] = "  nns_notify_time <='".$filter['notify_time_end']."'";
			}
			if(!empty($filter['nns_state'])){
				$state = $filter['nns_state'];
				switch($state){
				case 'request_state_succ':
					$wh_arr[] = " nns_result like '[0]%'";
					break;
				case 'request_state_fail':
					$wh_arr[] = " nns_result like '[-1]%'";
					break;
				case 'notify_state_wait':
					$wh_arr[] = " nns_notify_result is null ";
					break;
				case 'notify_state_succ':
					$wh_arr[] = " nns_notify_result='0'";
					break;
				case 'notify_state_fail':
					$wh_arr[] = " nns_notify_result='-1'";
					break;
				case 'resend_fail':
					$wh_arr[] = " nns_again=-1";
					break;
				}

			}	
			if(!empty($wh_arr))	$sql .= " and ".implode(" and ",$wh_arr);
			if(!empty($wh_arr))	$sql_count .= " and ".implode(" and ",$wh_arr);
		}
		$sql .= " order by nns_create_time desc ";
		$sql .= " limit $start,$size";
		//echo $sql;
		$data = nl_db_get_all($sql,$db);
		$rows = nl_db_get_col($sql_count,$db);
		return array('data'=>$data,'rows'=>$rows);
	}
	static public function delete_c2($ids=array()){
		$db = nn_get_db(NL_DB_WRITE);
		$db_r = nn_get_db(NL_DB_READ);
		$sql = "select nns_task_name from nns_mgtvbk_c2_log where ".nl_db_in($ids,'nns_id');
		$c2_info = nl_db_get_all($sql,$db_r);				
		$sql = "delete from nns_mgtvbk_c2_log where ".nl_db_in($ids,'nns_id');
		return nl_execute_by_db($sql,$db);
	}





	static  public function check_ftp_file($url){
		$url_arr = parse_url($url);
		$port = isset($url_arr["port"]) ? $url_arr["port"] : 21;
		$time = 10;
		$connect_no=ftp_connect($url_arr['host'],$port,$time);
		if ($connect_no===FALSE) return FALSE;

		@ftp_login(
			$connect_no,
			$url_arr["user"],
			$url_arr["pass"]
		);
		//吉林联通要开启被动模式
		@ftp_pasv($connect_no,true);
		$contents = @ftp_nlist($connect_no, $url_arr['path']);
		if($contents===false){
			return FALSE;
		}else{
			if(empty($contents)){
				return FALSE;
			}
			return true;
		}
	}
	
	
	
	
	static public function __gateway_run($url,$log=NULL,$method='get',$params=NULL,$header=NULL){
        if ($method=='get'){
            $data = http_build_query($params);
            if (strpos('?',$url)>0){
                $url .='&'.$data;
            }else{
                $url .='?'.$data;
            }
        }       
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if (is_array($header)){
            curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($method=='post'){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); //超时时间
        $output = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $reason = curl_error($ch);
        curl_close($ch);
        $return=array(
            'data'=>$output,
            'code'=>$code,
            'reason'=>$reason
        ); 
        return $return;
    }

}
